package galleryviewer.data;

import com.thoughtworks.xstream.XStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 *
 * @author jaccus
 */
public class DataLoader {
//    private static String configPath = "test/galleryviewer/data/singleLocalConfig.xml";
    private static String configPath = "conf/locals.xml";
    private static XStream xs;
    private static Map<Long, LocalBean> locals = new HashMap<Long, LocalBean>();
    
    static {
    	try {
	        xs = new XStream();
	        xs.alias("local", LocalBean.class);
	        xs.alias("locals", LinkedList.class);
	        xs.addImplicitCollection(LocalBean.class, "keywords", "keyword", String.class);
        
			loadLocals();
			
		} catch (IOException e) {
			e.printStackTrace();
		}
    }

    static void writeData(List<?> items) throws IOException {

        FileWriter fw = new FileWriter(configPath);
        xs.toXML(items, fw);
    }

    static Object readData() throws IOException {
        FileReader fr = new FileReader(configPath);

        Object items = xs.fromXML(fr);
        return items;
    }
    
    @SuppressWarnings("unchecked")
	private static void loadLocals() throws IOException {
    	List<LocalBean> localList = (List<LocalBean>) readData();
    	
        for (LocalBean local : localList) {
        	locals.put(local.getId(), local);
        }
    }
    
    public static LocalBean getLocal(long seed) {
    	Random random = new Random(seed);
    	long randomId = random.nextInt(locals.keySet().size()) + 1;
    	return locals.get(randomId);
    }
}
